<template>
  <a-card>
    <p>详情</p>
    <!--              table-->
    <vxe-table
      border
      show-overflow
      show-footer
      keep-source
      :is-hover="true"
      ref="xTable"
      :column-config="{ resizable: true }"
      min-height="400"
      :footer-method="footerMethod"
      :data="tableData"
      :edit-config="{
        trigger: 'click',
        mode: 'row',
        showStatus: true,
      }"
    >
      <vxe-column field="receipt_type" title="订单类型" sortable>
        <template #default="{ row }">
          {{ row.receipt_type == 1 ? "进货单" : "退货单" }}
        </template>
      </vxe-column>
      <vxe-column field="material" title="食材" sortable>
        <template #default="{ row }">
          {{ row.material.name }}
        </template>
      </vxe-column>

      <vxe-column field="supplier" title="供应商" sortable>
        <template #default="{ row }">
          {{ row.supplier.name }}
        </template>
      </vxe-column>
      <vxe-column field="qty" title="数量" sortable> </vxe-column>

      <vxe-column field="unit" title="单位" sortable> </vxe-column>
      <vxe-column field="unit_price" title="单价" sortable> </vxe-column>
      <vxe-column field="amount" title="金额" sortable> </vxe-column>
      <vxe-column field="created_at" title="时间" sortable> </vxe-column>
    </vxe-table>
    <!--              table-->
  </a-card>
</template>

<script setup lang="ts">
import Api from "@/api/backend/api";
const route = useRoute();
const order_id = route.params.order_id;

const tableData = ref([]);
const init = async () => {
  tableData.value = await Api.mPurchaseOrderController.detail({
    id: order_id,
  });
};

init();
const sumNum = (list: ReceiptItemModel[], field: string) => {
  let count = 0;
  list.forEach((item) => {
    count += item[field];
  });
  return count;
};

const countAmount = (row: ReceiptItemModel) => {
  row.qty = +row.qty;
  let mount = row.unit_price * row.qty;

  return mount;
};

const countAllAmount = (data: ReceiptItemModel[]) => {
  let count = 0;
  data.forEach((row) => {
    count = count + countAmount(row);
  });
  return count;
};


const footerMethod: VxeTablePropTypes.FooterMethod<ReceiptItemModel> = ({
  columns,
  data,
}) => {
  return [
    columns.map((column, columnIndex) => {
      if (columnIndex === 0) {
        return "合计";
      }
      if (columnIndex === 1) {
        //表单提交时会自动触发该事件。这个时候需要更新formData中的amount
        let count = countAllAmount(data);
        tableData.value.amount = count;
        return `共 ${count} 元`;
      }
      if (columnIndex === 6) {
        tableData.value.quantity = sumNum(data, "qty");
        return `数量： 共 ${sumNum(data, "qty")}`;
      }
      return "-";
    }),
  ];
};
</script>
<style></style>
